<template>
  <commonPage @updateReportCount="fetchCommentReportedCnt" :upOrgOptions="upOrgOptions" :tabKey="tabKey"
    v-if="tabKey === 1 || tabKey === 3">
    <a-tabs v-model:activeKey="tabKey" @change="changeTopTabs">
      <a-tab-pane :key="1" tab="评论列表">
      </a-tab-pane>
      <a-tab-pane :key="2" tab="禁言列表">
      </a-tab-pane>
      <a-tab-pane :key="3" :tab="`举报列表(${reporeConut})`">
      </a-tab-pane>
    </a-tabs>
  </commonPage>
  <div class="commentmanage-container" id="commentmanage-container" v-show="tabKey === 2">
    <div class="ant-spin-container">
      <div class="header-top">
        <a-tabs v-model:activeKey="tabKey" @change="changeTopTabs">
          <a-tab-pane :key="1" tab="评论列表">
          </a-tab-pane>
          <a-tab-pane :key="2" tab="禁言列表">
          </a-tab-pane>
          <a-tab-pane :key="3" :tab="`举报列表(${reporeConut})`">
          </a-tab-pane>
        </a-tabs>
      </div>
      <div class="forbid-container">
        <div class="forbid-header">
          <a-tabs type="card" v-model:activeKey="forbidKey" @change="changeForbidTabs" style="width:100%">
            <a-tab-pane :key="1" tab="禁言用户"></a-tab-pane>
            <a-tab-pane :key="2" tab="禁言IP"></a-tab-pane>
          </a-tabs>
          <a-input class="search-input" v-model:value="searchSlilence" :placeholder="forbidKey === 1 ? '搜索用户名' : '搜索IP'"
            @keyup.enter.native="toSearchInput()">
            <template #suffix>
              <i @click="toSearchInput()" class="iconfont icon-search"></i>
            </template>
          </a-input>
        </div>
        <div v-show="forbidKey === 1" style="margin-top: 16px;">
          <!-- 表格展示部分 -->
          <baseTable :pageSize="20" :simple="true" :columns="columns.forbidUserColumns" :dataSource="configData1.records"
            :isSelect="true" :scroll="scroll" ref="forbidTable1" :isShowPagination="isShowPagination"
            :showCheckDelete="showCheckDelete" :total="configData1.total" @changePage="changePage1">
            <template #bodyCell="{ column, text, record }">
              <template v-if="column.dataIndex === 'userName'">
                <a-tooltip placement="bottomLeft" v-if="text?.length * 14 > column.width">
                  <template #title>
                    <span>{{ text }}</span>
                  </template>
                  <a @click="toSingleMember(record.userName)" class="title-text">{{ text }}</a>
                </a-tooltip>
                <a @click="toSingleMember(record.userName)" v-else class="title-text">{{ text }}</a>
              </template>
              <template v-if="column.dataIndex === 'oparation'">
                <a-popconfirm placement="topRight" ok-text="确定" cancel-text="取消"
                  :disabled="!btnPerm.includes('relieveUserRemarkAble')" @confirm="confirmCancle([record.id], 1)">
                  <template #title>
                    <p style="width: 197px">是否确定解除用户禁止？</p>
                  </template>
                  <a :class="{ disable: !btnPerm.includes('relieveUserRemarkAble') }">{{ record.oparation[0] }}</a>
                </a-popconfirm>
              </template>
            </template>
            <template #otherOpration>
              <a-button @click="confirmCancle(rowSelection1, 2)"
                :disabled="!rowSelection1.length || !btnPerm.includes('relieveUserRemarkAble')">解除用户禁止</a-button>
            </template>
          </baseTable>

        </div>
        <div v-show="forbidKey === 2" style="margin-top: 16px;">
          <!-- 表格展示部分 -->
          <baseTable :pageSize="20" :simple="true" :columns="columns.forbidIpColumns" :dataSource="configData2.records"
            :isSelect="true" :scroll="scroll" ref="forbidTable2" :isShowPagination="isShowPagination"
            :showCheckDelete="showCheckDelete" :total="configData2.total" @changePage="changePage2">
            <template #bodyCell="{ column, text, record }">
              <template v-if="column.dataIndex === 'ipAddress'">
                <a @click="toSingleIp(record.ipAddress)" class="title-text">{{ text }}</a>
              </template>
              <template v-if="column.dataIndex === 'oparation'">
                <a-popconfirm placement="topRight" :disabled="!btnPerm.includes('relieveIPRemarkAble')"
                  @confirm="confirmCancle([record.id], 1)">
                  <template #title>
                    <p style="width: 197px">是否确定解除IP禁止？</p>
                  </template>
                  <a :class="{ disable: !btnPerm.includes('relieveIPRemarkAble') }">{{ record.oparation[0] }}</a>
                </a-popconfirm>
              </template>
            </template>
            <template #otherOpration>
              <a-button :style="{ 'margin-left': '8px' }" @click="confirmCancle(rowSelection2, 2)"
                :disabled="!rowSelection2.length || !btnPerm.includes('relieveIPRemarkAble')">解除IP禁止</a-button>
            </template>
          </baseTable>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { computed, nextTick, onMounted, createVNode, reactive, ref } from "vue"
import commonPage from './common.vue'
import { scrollType, modeProp, dataSourceType } from "@/type.d";
import { useRoute, useRouter } from "vue-router";
import baseTable from "@/components/table/baseTable.vue";
import request from "@/api/index";
import { Modal, message, TreeSelectProps } from "ant-design-vue";
// import tableToolTip from "@/components/table/tableToolTip.vue";
import { getTableScroll } from "@/components/table/tableConfig/table";
import columns from "@/components/table/tableConfig/columnsName";
import { routerPerm } from '@/utils/common';

// data
const btnPerm = ref<any[]>([]);
const router = useRouter();
const tabKey = ref<number>(1);
const forbidKey = ref<number>(1);
const reporeConut = ref<number>(0);
let rowSelection1 = ref<(string | number)[]>([]);
let rowSelection2 = ref<(string | number)[]>([]);
let upOrgOptions = ref<dataSourceType[]>([]);
const isShowPagination = true; // 是否需要配分页器
const showCheckDelete = true; // 是否需要分页器中的自定义全选和删除
let searchSlilence = ref<string>('');
const pageCurrent1 = ref<number>(1)
const pageSize1 = ref<number>(20)
const pageCurrent2 = ref<number>(1)
const pageSize2 = ref<number>(20)
let scroll: scrollType = reactive({ y: "", isFixed: false }); // 
const route = useRoute();
const forbidTable1 = ref<any>(null);
const forbidTable2 = ref<any>(null);

//method

//改变头部列表tab切换
const changeTopTabs = (activeKey: number) => {
  tabKey.value = activeKey;
  if (tabKey.value === 2) {
    forbidKey.value === 1 ? fetchSilencedUserPage() :
      fetchSilencedIpPage()
  } else if (tabKey.value === 3) {
    fetchCommentReportedCnt();
  }
};
//改禁言列表tab切换
const changeForbidTabs = (activeKey: number) => {
  searchSlilence.value = ''
  forbidKey.value = activeKey;
  forbidKey.value === 1 ? fetchSilencedUserPage() :
    fetchSilencedIpPage()
};


// computed
rowSelection1 = computed(() => {
  return forbidTable1.value.selectedRowKeys;
});
rowSelection2 = computed(() => {
  return forbidTable2.value.selectedRowKeys;
});

//表格数据
let configData1 = reactive<dataSourceType>({ total: 0, size: 20, records: [] });
let configData2 = reactive<dataSourceType>({ total: 0, size: 20, records: [] });

//搜索IP和用户
const toSearchInput = () => {
  if (forbidKey.value === 1) {
    fetchSilencedUserPage()
  } else {
    fetchSilencedIpPage()
  }
}

//切换分页器
const changePage1 = (data: { pageCurrent: any; pageSize: any }) => {
  pageCurrent1.value = data.pageCurrent;
  pageSize1.value = data.pageSize;
  fetchSilencedUserPage();
};
//切换分页器
const changePage2 = (data: { pageCurrent: any; pageSize: any }) => {
  pageCurrent2.value = data.pageCurrent;
  pageSize2.value = data.pageSize;
  fetchSilencedIpPage();
};

//获取禁言用户
const fetchSilencedUserPage = async () => {
  const data: {} = {
    pageNumber: pageCurrent1.value,
    pageSize: pageSize1.value,
    userName: searchSlilence.value,
  };
  const telData = (await request.fetchSilencedUserPage(data)) || {};
  let reqData = telData;
  let sourceData = reactive({});
  const records: any[] = [];
  reqData?.records?.map((item: any, index: number) => {
    sourceData = {
      createUser: item.createUser,
      groupName: item.groupName,
      userName: item.userName,
      oparation: ["解除用户禁止"],
      createTime: item.createTime,
      id: item.id,
    };
    records.push(sourceData);
  });
  configData1.total = reqData.total;
  configData1.size = reqData.size;
  configData1.records = records;
  nextTick(() => {
    scroll.y = getTableScroll(74, "commentmanage-container").y;
    scroll.isFixed = getTableScroll(74, "commentmanage-container").isFixed;
  });
}
//获取禁言IP
const fetchSilencedIpPage = async () => {
  const data: {} = {
    pageNumber: pageCurrent2.value,
    pageSize: pageSize2.value,
    ipAddress: searchSlilence.value,
  };
  const telData = (await request.fetchSilencedIpPage(data)) || {};
  let reqData = telData;
  let sourceData = reactive({});
  const records: any[] = [];
  reqData?.records?.map((item: any, index: number) => {
    sourceData = {
      createUser: item.createUser,
      oparation: ["解除IP禁止"],
      ipAddress: item.ipAddress,
      createTime: item.createTime,
      id: item.id,
    };
    records.push(sourceData);
  });
  configData2.total = reqData.total;
  configData2.size = reqData.size;
  configData2.records = records;
  nextTick(() => {
    scroll.y = getTableScroll(74, "commentmanage-container").y;
    scroll.isFixed = getTableScroll(74, "commentmanage-container").isFixed;
  });
}

//解除禁言
const confirmCancle = (ids: any[], type: number) => {
  if (type === 1) {
    cancleSlilence(ids)
  } else {
    Modal.confirm({
      content: `${forbidKey.value === 1 ? '您确定将选中的用户解除禁止？' : '您确定将选中的IP解除禁止？'}`,
      centered: true,
      icon: createVNode("i", {
        class: "iconfont icon-warn warning_ICON",
      }),
      cancelText: "取消",
      okText: "确定",
      onOk: async () => {
        cancleSlilence(ids)
      },
      onCancel() { },
    });
  }
}

//取消禁言
const cancleSlilence = (ids: any[]) => {
  request[forbidKey.value === 1 ? 'fetchSilencedUserCancelSilencedUser' : 'fetchSilencedIpCancelSilencedIp']({ ids })
    .then((res: any) => {
      if (res.code == "00000 00000") {
        forbidKey.value === 1 ? fetchSilencedUserPage() :
          fetchSilencedIpPage()
        message.success(res.message);
      } else {
        message.error(res.message);
      }
    })
    .catch((err: any) => {
      throw new Error(err);
    });
}


//前往单个会员评论列表
const toSingleMember = (commentator: string) => {
  router.push({
    path: "/interaction/singleMember",
    query: {
      commentator
    },
  });
}


//前往单个IP评论列表
const toSingleIp = (ipAddress: string) => {
  router.push({
    path: "/interaction/singleIp",
    query: {
      ipAddress
    },
  });
}

//被举报数目
const fetchCommentReportedCnt = async () => {
  reporeConut.value = await request.fetchCommentReportedCnt()
}
//获取新增层级树列表
const fetchChannelChannelTree = async () => {
  let datas = await request.fetchChannelChannelTree();
  datas.unshift({ id: '', channelName: '全部' })
  upOrgOptions.value = datas
};

onMounted(() => {
  btnPerm.value = routerPerm();
  fetchCommentReportedCnt()
  fetchSilencedUserPage()
  fetchSilencedIpPage()
  fetchChannelChannelTree()
})

</script>

<style lang="less" scoped>
.commentmanage-container {
  height: calc(100% - 72px);
  background-color: #fff;
  border-radius: 2px;
  padding: 16px;

  .header-top {
    border-bottom: 1px solid rgba(0, 0, 0, 0.06);

    ::v-deep(.ant-tabs-tab) {
      padding: 8px 0;
    }

    ::v-deep(.ant-tabs-top > .ant-tabs-nav::before, .ant-tabs-bottom > .ant-tabs-nav::before, .ant-tabs-top > div > .ant-tabs-nav::before, .ant-tabs-bottom > div > .ant-tabs-nav::before) {
      border: none;
    }
  }


  .forbid-container {
    display: flex;
    flex-direction: column;
    margin-top: 16px;

    .forbid-header {
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      position: relative;
    }

    ::v-deep(.ant-tabs-tab) {
      border: auto;
    }

    ::v-deep(.ant-tabs-card > .ant-tabs-nav .ant-tabs-tab, .ant-tabs-card > div > .ant-tabs-nav .ant-tabs-tab) {
      border: 1px solid #f0f0f0;
      transition: all 0.01s cubic-bezier(0.645, 0.045, 0.355, 1)
    }

    ::v-deep(.ant-tabs-card.ant-tabs-top > .ant-tabs-nav .ant-tabs-tab-active) {
      border-bottom: none;
    }

    .search-input {
      width: 192px;
      height: 32px;
      position: absolute;
      bottom: 9px;
      right: 0px;
    }
  }

  .title-text {
    max-width: 25px;
    text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;
  }
}

::v-deep(.ant-table-tbody > tr > td:nth-last-of-type(1)) {
  text-align: right;
  margin-right: 16px;
}
</style>
<style>
.ant-tabs-card.ant-tabs-top>.ant-tabs-nav .ant-tabs-tab+.ant-tabs-tab {
  margin-left: 2px;
}

.ant-tabs-card>.ant-tabs-nav .ant-tabs-tab {
  padding: 8px 16px;
}
</style>